using System;
using System.Data;
using System.Data.SqlClient;


namespace MushManager.DAL
{
	public class DALSqlEngine : DALEngine, MushManager.DAL.IDALSqlEngine
	{
		public DALSqlEngine(string connectionString) : base(connectionString)
		{
		}
	
		protected override IDbConnection GetConnection()
		{
			SqlConnection newConn = new SqlConnection(ConnectionString);
			newConn.Open();
			
			return newConn;
			
		}
		
		
		protected override IDbCommand CreateCommand(string spName)
		{
			SqlCommand cmd = new SqlCommand(spName, (SqlConnection)Connection);
			cmd.CommandType = CommandType.StoredProcedure;
		
			foreach (DALParameter param in Parameters)
			{
				SqlParameter sqlParam  = new SqlParameter(param.Name, param.Value);
				sqlParam.Direction     = param.Direction;				
				sqlParam.Value         = param.Value;
								
				cmd.Parameters.Add(sqlParam);
				
				if (param.Size != 0)
				{
					sqlParam.Size   = param.Size;
					sqlParam.DbType = param.Type;
				}							
			}
			
			return cmd;
		
		}

		public override void ExecSP_DataSet(string spName, DataSet dataSet, string tableName)
		{
			try
			{
				IDbCommand cmd = CreateCommand(spName);				
				SqlDataAdapter adapter = new SqlDataAdapter((SqlCommand)cmd);
				adapter.Fill(dataSet, tableName);
									
			}
			catch (Exception e)
			{				
				throw new DALException("Error in DALSqlEngine::ExecSP_DataSet, in stored procedure '" + spName + "'", e);
			}		
		}
		
		public override void ExecQuery_DataSet(string query, DataSet dataSet, string tableName)
		{		
			try
			{

				SqlDataAdapter adapter = new SqlDataAdapter(query, (SqlConnection)Connection);	
				adapter.Fill(dataSet, tableName);
									
			}
			catch (Exception e)
			{				
				throw new DALException("Error in DALSqlEngine::ExecQuery_DataSet, in query '" + query + "'", e);
			}		
		
		}
	}
}